<template>
  <main-card-admin
    :title="`应用详情（${appInfo.name}）`"
    :crumbs="crumbs"
    :screen-style-obj="{ padding: '0 0 20px 0' }"
    is-fixed-body
    :loading="loading"
  >
    <template #screen-space>
      <a-row class="time-module h-38">
        <a-col class="mr-16 label">应用创建时间</a-col>
        <a-col class="mr-24 val">{{ appInfo.createTime }}</a-col>
        <a-col class="mr-24">
          <svg xmlns="http://www.w3.org/2000/svg" width="2" height="20" viewBox="0 0 2 20" fill="none">
            <path d="M1 0V20" stroke="#D9D9DB" />
          </svg>
        </a-col>
        <a-col class="mr-16 label">应用更新时间</a-col>
        <a-col class="mr-24 val">{{ appInfo.updateTime }}</a-col>
      </a-row>
    </template>
    <div class="page-body">
      <!-- 应用信息 -->
      <app-info :info-arr="appInfoArr" :app-id="appId" />
      <div class="tabs">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane v-for="tab in tabs" :key="tab.key" :tab="tab.name">
            <a-space direction="vertical" class="w-[100%]">
              <!-- API服务 -->
              <template v-if="activeKey === 1">
                <a-collapse v-for="apiItem in appInfo.apiVOList" :key="apiItem.id">
                  <a-collapse-panel key="1" :header="apiItem.algoName">
                    <a-table
                      :style="{ width: '100%' }"
                      :scroll="{ x: 'auto' }"
                      :columns="apiTableColumns"
                      :data-source="apiItem.appServeList"
                      :pagination="false"
                    >
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex == 'version'"> {{ record.version }} </template>
                        <template v-else-if="column.dataIndex == 'usedCallNum'">
                          {{ record.usedCallNum }}/{{ record.totalCallNum }}
                        </template>
                        <template v-else-if="column.dataIndex == 'operateMethodStatus'">
                          <a-tooltip v-if="statusObj[record.operateMethodStatus].tooltip" placement="bottom">
                            <template #title>
                              <span>{{ record.operateMethodStatus?.substring(1) }}时间 {{ record?.operateMethodTime || '' }}</span>
                            </template>
                            {{ record.operateMethodStatus || '' }}
                          </a-tooltip>
                          <span v-else>{{ record.operateMethodStatus || '' }}</span>
                        </template>
                        <template v-else-if="column.dataIndex == 'time'">
                          {{ record.beforeValidTime }} ~ {{ record.afterValidTime }}
                        </template>
                        <template v-else-if="column.dataIndex == 'docs'">
                          <a-button type="link" @click="previewDoc(record.operateMethodId)"> 技术文档</a-button>
                        </template>
                        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
                      </template>
                    </a-table>
                  </a-collapse-panel>
                </a-collapse>
                <a-empty v-if="appInfo.apiVOList?.length === 0" :image="simpleImage" />
              </template>
              <!-- SDK服务 -->
              <template v-else-if="activeKey === 2">
                <a-collapse v-for="askItem in appInfo.sdkVOList" :key="askItem.id">
                  <a-collapse-panel key="1" :header="askItem.algoName">
                    <a-table
                      :style="{ width: '100%' }"
                      :scroll="{ x: 'auto' }"
                      :columns="sdkTableColumns"
                      :data-source="askItem.appServeList"
                      :pagination="false"
                    >
                      <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex == 'version'"> {{ record.version }} </template>
                        <template v-else-if="column.dataIndex == 'authType'">
                          {{ record.authType === 1 ? '联网激活' : '离线激活' }}
                        </template>
                        <template v-else-if="column.dataIndex == 'openNum'">
                          {{ record.authType === 1 ? record.usedActivateNum : '-' }}/{{ record.totalActivateNum }}
                        </template>
                        <template v-else-if="column.dataIndex == 'tools'">
                          <a-space>
                            <a-button type="link" @click="handleOpenDeviceCodeModal(record.id)">设备码</a-button>
                            <a-button
                              v-if="isAdmin && checkKey('user-list-sdk-download')"
                              type="link"
                              @click="downloadSdk(record.operateMethodId)"
                            >
                              下载
                            </a-button>
                            <a-button
                              v-else-if="!isAdmin && checkKey('student-list-sdk-download')"
                              type="link"
                              @click="downloadSdk(record.operateMethodId)"
                            >
                              下载
                            </a-button>
                            <a-button type="link" @click="previewDoc(record.operateMethodId)"> 技术文档</a-button>
                          </a-space>
                        </template>
                        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
                      </template>
                    </a-table>
                  </a-collapse-panel>
                </a-collapse>
                <a-empty v-if="appInfo.sdkVOList?.length === 0" :image="simpleImage" />
              </template>
            </a-space>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </main-card-admin>

  <device-code ref="deviceCodeRef" />
</template>

<script lang="ts" setup>
  import { Empty, message } from 'ant-design-vue'
  import { computed, ref, watch } from 'vue'
  import { provide } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import { Crumb } from '@/components/MainCard/index.vue'
  import { checkKey } from '@/directives/auth'
  import { appApi, clientApi } from '@/services/api'
  import { fetchDownload } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  // eslint-disable-next-line
  import AppInfo, { ArrItem } from './components/AppInfo.vue'
  import DeviceCode from './components/DeviceCode.vue'
  import { statusObj } from './options'
  import { AppDetail } from './types'
  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

  const route = useRoute()

  /* 用户详情-------------------------------------------------------------------- */
  const isAdmin = ref(false)

  /**
   * 获取用户是否管理员（用于更改面包屑）
   * @param id
   */
  const getUserIsAdmin = async (id: string) => {
    const { data } = await clientApi.detail(id)()
    isAdmin.value = data.roleType === 2
  }

  /* -------------------------------------------------------------------- */

  //将isAdmin注入到全局
  provide('isAdmin', isAdmin)

  const crumbs = computed<Crumb[]>(() => [
    isAdmin.value
      ? {
          name: '管理员',
          path: '/user-manage/admin-list'
        }
      : {
          name: '普通用户',
          path: '/user-manage/student-list'
        },
    {
      name: `账号详情（${appInfo.value.username || ''}）`,
      path: `/user-manage/detail/${appInfo.value.uid}`
    },
    {
      name: `应用详情（${appInfo.value.name}）`
    }
  ])

  const appId = (route.params.id as string) || ''
  const appInfo = ref<AppDetail>({})
  const appInfoArr = ref<ArrItem[]>([]) // 应用信息数组
  const activeKey = ref<1 | 2>(1) // 1:API服务 2:SDK服务
  const tabs = computed(() => [
    {
      key: 1,
      name: `API服务`
    },
    {
      key: 2,
      name: `SDK服务`
    }
  ])

  watch(appInfo, val => {
    appInfoArr.value = [
      { label: '应用编号', val: val.number || '' },
      { label: '应用名称', val: val.name || '' },
      { label: '在线服务ID', val: val.onlineId || '' },
      { label: 'API Key', val: val.apiKey || '' },
      { label: 'Secret Key', val: val.secretKey || '' },
      { label: 'License ID', val: val.licenseId || '', type: 'license' },
      { label: '序列号', val: val.serialNum || '' },
      { label: '应用描述', val: val.content || '' }
    ]
  })

  const { loading, runAsync: getClientInfoRun } = useRequest<ResponseData<AppDetail>>(clientApi.lifecycleDetailsType4(appId), {
    onSuccess: res => {
      appInfo.value = res.data
      getUserIsAdmin(appInfo.value.uid)
    }
  })

  const getClientInfo = async () => {
    getClientInfoRun({
      appServeType: activeKey.value
    })
  }

  watch(activeKey, () => getClientInfo(), { immediate: true })

  // 下载sdk文件
  const downloadSdk = async (operateMethodId: string) => {
    try {
      const { data } = await clientApi.downloadSdk(operateMethodId)()
      fetchDownload(data.fileUrl, data.fileName)
      message.success({ content: '文件下载成功', key: 'downloading', duration: 2 })
    } catch (error) {
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }

  // 设备码
  const deviceCodeRef = ref()
  const handleOpenDeviceCodeModal = async (id: string) => {
    try {
      deviceCodeRef.value.openModal()
      deviceCodeRef.value.changeLoading(true)
      const { data } = await appApi.getSerialDeviceCode(id)()
      deviceCodeRef.value.changeLoading(false)
      deviceCodeRef.value.setDetailInfo(data)
    } catch (error) {
      deviceCodeRef.value.changeLoading(false)
    }
  }

  const previewDoc = async (operateId: string) => {
    const { data } = await appApi.getDownloadDocumentUrl({}, { urlParams: { operateId } })
    window.open(data.fileUrl)
  }
  /* API,SDK展示逻辑-------------------------------------------------------------------- */
  const apiTableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: 'APICode',
        dataIndex: 'apiCode',
        width: 100
      },
      {
        title: '调用量',
        dataIndex: 'usedCallNum',
        width: 100
      },
      {
        title: 'QPS',
        dataIndex: 'qps',
        width: 100
      },
      {
        title: '应用服务状态',
        dataIndex: 'appStatus',
        width: 120
      },
      {
        title: '算法运行状态',
        dataIndex: 'operateMethodStatus',
        width: 120
      },
      {
        title: '有效期',
        dataIndex: 'time',
        minWidth: 200
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 190
      },
      {
        title: '',
        dataIndex: 'docs',
        width: 190
      }
    ])
  )
  const sdkTableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: '平台',
        dataIndex: 'platform',
        width: 180
      },
      {
        title: '语言',
        dataIndex: 'language',
        width: 100
      },
      {
        title: '授权方式',
        dataIndex: 'authType',
        width: 140
      },
      {
        title: '已激活/可激活设备数',
        dataIndex: 'openNum',
        width: 160
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 160
      },
      {
        title: '',
        dataIndex: 'tools'
      }
    ])
  )
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';

  .time-module {
    display: flex;
    align-items: center;
    padding: 8px 24px;
    font-size: 12px;
    background: @background3;
    border-radius: 6px;

    .label {
      color: @text03;
    }

    .val {
      color: @text01;
    }
  }

  .page-body {
    display: flex;
    height: 100%;

    .tabs {
      flex: 1;
      // height: 100%;
      display: flex;
      overflow: hidden;

      .ant-tabs {
        width: 100%;

        :deep(.ant-tabs-content-holder) {
          overflow-y: auto;
        }
      }

      .ant-collapse {
        width: 100%;

        :deep(.ant-collapse-content-box) {
          padding: 0;
        }
      }
    }
  }
</style>
